#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/11 11:29
# @Author  : jeff
# @FileName: base_service
from datetime import datetime

from src.model.base_model import db
from functools import wraps
from loguru import logger
from src.enums.status_enum import Status
from sqlalchemy import exc


class BaseService(object):
    """
    Enable interface-level transactions, submit transactions uniformly, and handle exceptions uniformly
    """

    @staticmethod
    def transactional(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            with db.session.begin(
                    nested=True):  # Open transactions, nest transactions, and automatically close transactions with
                try:
                    res = func(*args, **kwargs)
                    db.session.commit()  # Submit transactions and submit them uniformly at the interface level
                    logger.info(f'commit success')
                except exc.SQLAlchemyError as e:
                    logger.error(e)
                    db.session.rollback()
                    return Status.REPEAT_MESSAGE
                except Exception as e:
                    logger.error(e)
                    db.session.rollback()
                    return Status.GENERIC_ERROR  # Returns a generic error message
            return res

        return wrapper

    @classmethod
    def get_current_time(cls):
        """
        Get current time
        :return:
        """
        return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
